package com.shujia

import scala.collection.mutable
import scala.io.{BufferedSource, Source}

object Demo03WordCountScala {
  def main(args: Array[String]): Unit = {
    // 尝试在Scala中实现wordCount
    val bs: BufferedSource = Source
      .fromFile("scala/data/words.txt")

    val wordCntMap: mutable.HashMap[String, Integer] = mutable.HashMap[String, Integer]()

    for (line <- bs.getLines()) {
      val wordsArr: Array[String] = line.split(",")
      for (word <- wordsArr) {
        if (!wordCntMap.contains(word)) {
          wordCntMap.put(word, 1)
        } else {
          wordCntMap.put(word, wordCntMap(word) + 1)
        }
      }
    }

    println(wordCntMap)


    bs.close()

    Source
      .fromFile("scala/data/words.txt")
      .getLines()
      .toList
      .flatMap(_.split(","))
      .groupBy(word=>word)
      .map(kv=>s"${kv._1},${kv._2.size}")
      .foreach(println)
  }

}
